import * as vscode from 'vscode';
import { Snippet, SnippetManager } from '../utils/snippetManager';

export class SnippetProvider implements vscode.TreeDataProvider<SnippetItem> {
    private _onDidChangeTreeData: vscode.EventEmitter<SnippetItem | undefined | null | void> = new vscode.EventEmitter();
    readonly onDidChangeTreeData: vscode.Event<SnippetItem | undefined | null | void> = this._onDidChangeTreeData.event;

    constructor(private snippetManager: SnippetManager) {}

    refresh(): void {
        this._onDidChangeTreeData.fire();
    }

    getTreeItem(element: SnippetItem): vscode.TreeItem {
        return element;
    }

    getChildren(element?: SnippetItem): Thenable<SnippetItem[]> {
        if (!element) {
            // 根节点：显示分组
            const groups = this.snippetManager.getGroups();
            if (groups.length === 0) {
                return Promise.resolve([new SnippetItem('No snippets', vscode.TreeItemCollapsibleState.None, 'empty')]);
            }
            return Promise.resolve(groups.map(group => 
                new SnippetItem(group, vscode.TreeItemCollapsibleState.Collapsed, 'group', group)
            ));
        } else if (element.contextValue === 'group') {
            // 分组下的代码片段
            const snippets = this.snippetManager.getSnippetsByGroup(element.label as string);
            return Promise.resolve(snippets.map(snippet => 
                new SnippetItem(
                    snippet.name, 
                    vscode.TreeItemCollapsibleState.None, 
                    'snippet', 
                    snippet.group,
                    snippet
                )
            ));
        }
        
        return Promise.resolve([]);
    }
}

export class SnippetItem extends vscode.TreeItem {
    constructor(
        public readonly label: string,
        public readonly collapsibleState: vscode.TreeItemCollapsibleState,
        public readonly contextValue: string,
        public readonly group?: string,
        public readonly snippet?: Snippet
    ) {
        super(label, collapsibleState);
        
        if (contextValue === 'snippet' && snippet) {
            this.tooltip = `${snippet.description}\n\n${snippet.code}`;
            this.description = snippet.description;
            this.command = {
                command: 'snippetManager.insertSnippet',
                title: 'Insert Snippet',
                arguments: [snippet]
            };
            this.iconPath = new vscode.ThemeIcon('code');
        } else if (contextValue === 'group') {
            this.iconPath = new vscode.ThemeIcon('folder');
        } else if (contextValue === 'empty') {
            this.iconPath = new vscode.ThemeIcon('info');
        }
    }
}
